5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = [
51 'login' => 'ApiLogin',
52 'clientlogin' => 'ApiClientLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiAMCreateAccount',
55 'linkaccount' => 'ApiLinkAccount',
56 'unlinkaccount' => 'ApiRemoveAuthenticationData',
57 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
58 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
59 'resetpassword' => 'ApiResetPassword',
60 'query' => 'ApiQuery',
61 'expandtemplates' => 'ApiExpandTemplates',
62 'parse' => 'ApiParse',
63 'stashedit' => 'ApiStashEdit',
64 'opensearch' => 'ApiOpenSearch',
65 'feedcontributions' => 'ApiFeedContributions',
66 'feedrecentchanges' => 'ApiFeedRecentChanges',
67 'feedwatchlist' => 'ApiFeedWatchlist',
69 'paraminfo' => 'ApiParamInfo',
71 'compare' => 'ApiComparePages',
72 'tokens' => 'ApiTokens',
73 'checktoken' => 'ApiCheckToken',
74 'cspreport' => 'ApiCSPReport',
77 'purge' => 'ApiPurge',
78 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
79 'rollback' => 'ApiRollback',
80 'delete' => 'ApiDelete',
81 'undelete' => 'ApiUndelete',
82 'protect' => 'ApiProtect',
83 'block' => 'ApiBlock',
84 'unblock' => 'ApiUnblock',
86 'edit' => 'ApiEditPage',
87 'upload' => 'ApiUpload',
88 'filerevert' => 'ApiFileRevert',
89 'emailuser' => 'ApiEmailUser',
90 'watch' => 'ApiWatch',
91 'patrol' => 'ApiPatrol',
92 'import' => 'ApiImport',
93 'clearhasmsg' => 'ApiClearHasMsg',
94 'userrights' => 'ApiUserrights',
95 'options' => 'ApiOptions',
96 'imagerotate' => 'ApiImageRotate',
97 'revisiondelete' => 'ApiRevisionDelete',
98 'managetags' => 'ApiManageTags',
100 'mergehistory' => 'ApiMergeHistory',
104 * List of available formats: format name => format class
106 private static $Formats = [
107 'json' => 'ApiFormatJson',
108 'jsonfm' => 'ApiFormatJson',
109 'php' => 'ApiFormatPhp',
110 'phpfm' => 'ApiFormatPhp',
111 'xml' => 'ApiFormatXml',
112 'xmlfm' => 'ApiFormatXml',
113 'rawfm' => 'ApiFormatJson',
114 'none' => 'ApiFormatNone',
117 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
119 * List of user roles that are specifically relevant to the API.
120 * array( 'right' => array ( 'msg' => 'Some message with a $1',
121 * 'params' => array ( $someVarToSubst ) ),
124 private static $mRights = [
126 'msg' => 'right-writeapi',
130 'msg' => 'api-help-right-apihighlimits',
131 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
134 // @codingStandardsIgnoreEnd
141 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
143 private $mEnableWrite;
144 private $mInternalMode, $mSquidMaxage;
148 private $mCacheMode = 'private';
149 private $mCacheControl = [];
150 private $mParamsUsed = [];
152 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
153 private $lacksSameOriginSecurity = null;
156 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
158 * @param IContextSource|WebRequest $context If this is an instance of
159 * FauxRequest, errors are thrown and no printing occurs
160 * @param bool $enableWrite Should be set to true if the api may modify data
162 public function __construct( $context = null, $enableWrite = false ) {
163 if ( $context === null ) {
164 $context = RequestContext
::getMain();
165 } elseif ( $context instanceof WebRequest
) {
168 $context = RequestContext
::getMain();
170 // We set a derivative context so we can change stuff later
171 $this->setContext( new DerivativeContext( $context ) );
173 if ( isset( $request ) ) {
174 $this->getContext()->setRequest( $request );
177 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
179 // Special handling for the main module: $parent === $this
180 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
182 if ( !$this->mInternalMode
) {
183 // Impose module restrictions.
184 // If the current user cannot read,
185 // Remove all modules other than login
188 if ( $this->lacksSameOriginSecurity() ) {
189 // If we're in a mode that breaks the same-origin policy, strip
190 // user credentials for security.
191 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
192 $wgUser = new User();
193 $this->getContext()->setUser( $wgUser );
197 $uselang = $this->getParameter( 'uselang' );
198 if ( $uselang === 'user' ) {
199 // Assume the parent context is going to return the user language
200 // for uselang=user (see T85635).
202 if ( $uselang === 'content' ) {
204 $uselang = $wgContLang->getCode();
206 $code = RequestContext
::sanitizeLangCode( $uselang );
207 $this->getContext()->setLanguage( $code );
208 if ( !$this->mInternalMode
) {
210 $wgLang = $this->getContext()->getLanguage();
211 RequestContext
::getMain()->setLanguage( $wgLang );
215 $config = $this->getConfig();
216 $this->mModuleMgr
= new ApiModuleManager( $this );
217 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
218 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
219 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
220 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
222 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
224 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
225 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
226 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
227 $this->mResult
->setMainForContinuation( $this );
228 $this->mContinuationManager
= null;
229 $this->mEnableWrite
= $enableWrite;
231 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
232 $this->mCommit
= false;
236 * Return true if the API was started by other PHP code using FauxRequest
239 public function isInternalMode() {
240 return $this->mInternalMode
;
244 * Get the ApiResult object associated with current request
248 public function getResult() {
249 return $this->mResult
;
253 * Get the security flag for the current request
256 public function lacksSameOriginSecurity() {
257 if ( $this->lacksSameOriginSecurity
!== null ) {
258 return $this->lacksSameOriginSecurity
;
261 $request = $this->getRequest();
264 if ( $request->getVal( 'callback' ) !== null ) {
265 $this->lacksSameOriginSecurity
= true;
269 // Header to be used from XMLHTTPRequest when the request might
270 // otherwise be used for XSS.
271 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
272 $this->lacksSameOriginSecurity
= true;
276 // Allow extensions to override.
277 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
278 return $this->lacksSameOriginSecurity
;
282 * Get the ApiErrorFormatter object associated with current request
283 * @return ApiErrorFormatter
285 public function getErrorFormatter() {
286 return $this->mErrorFormatter
;
290 * Get the continuation manager
291 * @return ApiContinuationManager|null
293 public function getContinuationManager() {
294 return $this->mContinuationManager
;
298 * Set the continuation manager
299 * @param ApiContinuationManager|null
301 public function setContinuationManager( $manager ) {
302 if ( $manager !== null ) {
303 if ( !$manager instanceof ApiContinuationManager
) {
304 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
305 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
308 if ( $this->mContinuationManager
!== null ) {
309 throw new UnexpectedValueException(
310 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
311 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
315 $this->mContinuationManager
= $manager;
319 * Get the API module object. Only works after executeAction()
323 public function getModule() {
324 return $this->mModule
;
328 * Get the result formatter object. Only works after setupExecuteAction()
330 * @return ApiFormatBase
332 public function getPrinter() {
333 return $this->mPrinter
;
337 * Set how long the response should be cached.
341 public function setCacheMaxAge( $maxage ) {
342 $this->setCacheControl( [
343 'max-age' => $maxage,
344 's-maxage' => $maxage
349 * Set the type of caching headers which will be sent.
351 * @param string $mode One of:
352 * - 'public': Cache this object in public caches, if the maxage or smaxage
353 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
354 * not provided by any of these means, the object will be private.
355 * - 'private': Cache this object only in private client-side caches.
356 * - 'anon-public-user-private': Make this object cacheable for logged-out
357 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
358 * set consistently for a given URL, it cannot be set differently depending on
359 * things like the contents of the database, or whether the user is logged in.
361 * If the wiki does not allow anonymous users to read it, the mode set here
362 * will be ignored, and private caching headers will always be sent. In other words,
363 * the "public" mode is equivalent to saying that the data sent is as public as a page
366 * For user-dependent data, the private mode should generally be used. The
367 * anon-public-user-private mode should only be used where there is a particularly
368 * good performance reason for caching the anonymous response, but where the
369 * response to logged-in users may differ, or may contain private data.
371 * If this function is never called, then the default will be the private mode.
373 public function setCacheMode( $mode ) {
374 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
375 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
377 // Ignore for forwards-compatibility
381 if ( !User
::isEveryoneAllowed( 'read' ) ) {
382 // Private wiki, only private headers
383 if ( $mode !== 'private' ) {
384 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
390 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
391 // User language is used for i18n, so we don't want to publicly
392 // cache. Anons are ok, because if they have non-default language
393 // then there's an appropriate Vary header set by whatever set
394 // their non-default language.
395 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
396 "'anon-public-user-private' due to uselang=user\n" );
397 $mode = 'anon-public-user-private';
400 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
401 $this->mCacheMode
= $mode;
405 * Set directives (key/value pairs) for the Cache-Control header.
406 * Boolean values will be formatted as such, by including or omitting
407 * without an equals sign.
409 * Cache control values set here will only be used if the cache mode is not
410 * private, see setCacheMode().
412 * @param array $directives
414 public function setCacheControl( $directives ) {
415 $this->mCacheControl
= $directives +
$this->mCacheControl
;
419 * Create an instance of an output formatter by its name
421 * @param string $format
423 * @return ApiFormatBase
425 public function createPrinterByName( $format ) {
426 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
427 if ( $printer === null ) {
428 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
435 * Execute api request. Any errors will be handled if the API was called by the remote client.
437 public function execute() {
438 if ( $this->mInternalMode
) {
439 $this->executeAction();
441 $this->executeActionWithErrorHandling();
446 * Execute an action, and in case of an error, erase whatever partial results
447 * have been accumulated, and replace it with an error message and a help screen.
449 protected function executeActionWithErrorHandling() {
450 // Verify the CORS header before executing the action
451 if ( !$this->handleCORS() ) {
452 // handleCORS() has sent a 403, abort
456 // Exit here if the request method was OPTIONS
457 // (assume there will be a followup GET or POST)
458 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
462 // In case an error occurs during data output,
463 // clear the output buffer and print just the error information
464 $obLevel = ob_get_level();
467 $t = microtime( true );
470 $this->executeAction();
471 $runTime = microtime( true ) - $t;
472 $this->logRequest( $runTime );
473 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
474 $this->getStats()->timing(
475 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
478 } catch ( Exception
$e ) {
479 $this->handleException( $e );
480 $this->logRequest( microtime( true ) - $t, $e );
484 // Commit DBs and send any related cookies and headers
485 MediaWiki
::preOutputCommit( $this->getContext() );
487 // Send cache headers after any code which might generate an error, to
488 // avoid sending public cache headers for errors.
489 $this->sendCacheHeaders( $isError );
491 // Executing the action might have already messed with the output
493 while ( ob_get_level() > $obLevel ) {
499 * Handle an exception as an API response
502 * @param Exception $e
504 protected function handleException( Exception
$e ) {
505 // Bug 63145: Rollback any open database transactions
506 if ( !( $e instanceof UsageException
) ) {
507 // UsageExceptions are intentional, so don't rollback if that's the case
509 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
510 } catch ( DBError
$e2 ) {
511 // Rollback threw an exception too. Log it, but don't interrupt
512 // our regularly scheduled exception handling.
513 MWExceptionHandler
::logException( $e2 );
517 // Allow extra cleanup and logging
518 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
521 if ( !( $e instanceof UsageException
) ) {
522 MWExceptionHandler
::logException( $e );
525 // Handle any kind of exception by outputting properly formatted error message.
526 // If this fails, an unhandled exception should be thrown so that global error
527 // handler will process and log it.
529 $errCode = $this->substituteResultWithError( $e );
531 // Error results should not be cached
532 $this->setCacheMode( 'private' );
534 $response = $this->getRequest()->response();
535 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
536 if ( $e->getCode() === 0 ) {
537 $response->header( $headerStr );
539 $response->header( $headerStr, true, $e->getCode() );
542 // Reset and print just the error message
545 // Printer may not be initialized if the extractRequestParams() fails for the main module
546 $this->createErrorPrinter();
549 $this->printResult( true );
550 } catch ( UsageException
$ex ) {
551 // The error printer itself is failing. Try suppressing its request
552 // parameters and redo.
554 'Error printer failed (will retry without params): ' . $ex->getMessage()
556 $this->mPrinter
= null;
557 $this->createErrorPrinter();
558 $this->mPrinter
->forceDefaultParams();
559 $this->printResult( true );
564 * Handle an exception from the ApiBeforeMain hook.
566 * This tries to print the exception as an API response, to be more
567 * friendly to clients. If it fails, it will rethrow the exception.
570 * @param Exception $e
573 public static function handleApiBeforeMainException( Exception
$e ) {
577 $main = new self( RequestContext
::getMain(), false );
578 $main->handleException( $e );
579 $main->logRequest( 0, $e );
580 } catch ( Exception
$e2 ) {
581 // Nope, even that didn't work. Punt.
585 // Reset cache headers
586 $main->sendCacheHeaders( true );
592 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
594 * If no origin parameter is present, nothing happens.
595 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
596 * is set and false is returned.
597 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
598 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
600 * http://www.w3.org/TR/cors/#resource-requests
601 * http://www.w3.org/TR/cors/#resource-preflight-requests
603 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
605 protected function handleCORS() {
606 $originParam = $this->getParameter( 'origin' ); // defaults to null
607 if ( $originParam === null ) {
608 // No origin parameter, nothing to do
612 $request = $this->getRequest();
613 $response = $request->response();
615 // Origin: header is a space-separated list of origins, check all of them
616 $originHeader = $request->getHeader( 'Origin' );
617 if ( $originHeader === false ) {
620 $originHeader = trim( $originHeader );
621 $origins = preg_split( '/\s+/', $originHeader );
624 if ( !in_array( $originParam, $origins ) ) {
625 // origin parameter set but incorrect
626 // Send a 403 response
627 $response->statusHeader( 403 );
628 $response->header( 'Cache-Control: no-cache' );
629 echo "'origin' parameter does not match Origin header\n";
634 $config = $this->getConfig();
635 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
637 $config->get( 'CrossSiteAJAXdomains' ),
638 $config->get( 'CrossSiteAJAXdomainExceptions' )
641 if ( $matchOrigin ) {
642 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
643 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
645 // This is a CORS preflight request
646 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
647 // If method is not a case-sensitive match, do not set any additional headers and terminate.
650 // We allow the actual request to send the following headers
651 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
652 if ( $requestedHeaders !== false ) {
653 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
656 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
659 // We only allow the actual request to be GET or POST
660 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
663 $response->header( "Access-Control-Allow-Origin: $originHeader" );
664 $response->header( 'Access-Control-Allow-Credentials: true' );
665 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
666 $response->header( "Timing-Allow-Origin: $originHeader" );
670 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
675 $this->getOutput()->addVaryHeader( 'Origin' );
680 * Attempt to match an Origin header against a set of rules and a set of exceptions
681 * @param string $value Origin header
682 * @param array $rules Set of wildcard rules
683 * @param array $exceptions Set of wildcard rules
684 * @return bool True if $value matches a rule in $rules and doesn't match
685 * any rules in $exceptions, false otherwise
687 protected static function matchOrigin( $value, $rules, $exceptions ) {
688 foreach ( $rules as $rule ) {
689 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
690 // Rule matches, check exceptions
691 foreach ( $exceptions as $exc ) {
692 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
705 * Attempt to validate the value of Access-Control-Request-Headers against a list
706 * of headers that we allow the follow up request to send.
708 * @param string $requestedHeaders Comma seperated list of HTTP headers
709 * @return bool True if all requested headers are in the list of allowed headers
711 protected static function matchRequestedHeaders( $requestedHeaders ) {
712 if ( trim( $requestedHeaders ) === '' ) {
715 $requestedHeaders = explode( ',', $requestedHeaders );
716 $allowedAuthorHeaders = array_flip( [
717 /* simple headers (see spec) */
722 /* non-authorable headers in XHR, which are however requested by some UAs */
726 /* MediaWiki whitelist */
729 foreach ( $requestedHeaders as $rHeader ) {
730 $rHeader = strtolower( trim( $rHeader ) );
731 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
732 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
740 * Helper function to convert wildcard string into a regex
744 * @param string $wildcard String with wildcards
745 * @return string Regular expression
747 protected static function wildcardToRegex( $wildcard ) {
748 $wildcard = preg_quote( $wildcard, '/' );
749 $wildcard = str_replace(
755 return "/^https?:\/\/$wildcard$/";
759 * Send caching headers
760 * @param bool $isError Whether an error response is being output
761 * @since 1.26 added $isError parameter
763 protected function sendCacheHeaders( $isError ) {
764 $response = $this->getRequest()->response();
765 $out = $this->getOutput();
767 $out->addVaryHeader( 'Treat-as-Untrusted' );
769 $config = $this->getConfig();
771 if ( $config->get( 'VaryOnXFP' ) ) {
772 $out->addVaryHeader( 'X-Forwarded-Proto' );
775 if ( !$isError && $this->mModule
&&
776 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
778 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
779 if ( $etag !== null ) {
780 $response->header( "ETag: $etag" );
782 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
783 if ( $lastMod !== null ) {
784 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
788 // The logic should be:
789 // $this->mCacheControl['max-age'] is set?
790 // Use it, the module knows better than our guess.
791 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
792 // Use 0 because we can guess caching is probably the wrong thing to do.
793 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
795 if ( isset( $this->mCacheControl
['max-age'] ) ) {
796 $maxage = $this->mCacheControl
['max-age'];
797 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
798 $this->mCacheMode
!== 'private'
800 $maxage = $this->getParameter( 'maxage' );
802 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
804 if ( $this->mCacheMode
== 'private' ) {
805 $response->header( "Cache-Control: $privateCache" );
809 $useKeyHeader = $config->get( 'UseKeyHeader' );
810 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
811 $out->addVaryHeader( 'Cookie' );
812 $response->header( $out->getVaryHeader() );
813 if ( $useKeyHeader ) {
814 $response->header( $out->getKeyHeader() );
815 if ( $out->haveCacheVaryCookies() ) {
816 // Logged in, mark this request private
817 $response->header( "Cache-Control: $privateCache" );
820 // Logged out, send normal public headers below
821 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
822 // Logged in or otherwise has session (e.g. anonymous users who have edited)
823 // Mark request private
824 $response->header( "Cache-Control: $privateCache" );
827 } // else no Key and anonymous, send public headers below
830 // Send public headers
831 $response->header( $out->getVaryHeader() );
832 if ( $useKeyHeader ) {
833 $response->header( $out->getKeyHeader() );
836 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
837 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
838 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
840 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
841 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
844 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
845 // Public cache not requested
846 // Sending a Vary header in this case is harmless, and protects us
847 // against conditional calls of setCacheMaxAge().
848 $response->header( "Cache-Control: $privateCache" );
853 $this->mCacheControl
['public'] = true;
855 // Send an Expires header
856 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
857 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
858 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
860 // Construct the Cache-Control header
863 foreach ( $this->mCacheControl
as $name => $value ) {
864 if ( is_bool( $value ) ) {
866 $ccHeader .= $separator . $name;
870 $ccHeader .= $separator . "$name=$value";
875 $response->header( "Cache-Control: $ccHeader" );
879 * Create the printer for error output
881 private function createErrorPrinter() {
882 if ( !isset( $this->mPrinter
) ) {
883 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
884 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
885 $value = self
::API_DEFAULT_FORMAT
;
887 $this->mPrinter
= $this->createPrinterByName( $value );
890 // Printer may not be able to handle errors. This is particularly
891 // likely if the module returns something for getCustomPrinter().
892 if ( !$this->mPrinter
->canPrintErrors() ) {
893 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
898 * Create an error message for the given exception.
900 * If the exception is a UsageException then
901 * UsageException::getMessageArray() will be called to create the message.
903 * @param Exception $e
904 * @return array ['code' => 'some string', 'info' => 'some other string']
907 protected function errorMessageFromException( $e ) {
908 if ( $e instanceof UsageException
) {
909 // User entered incorrect parameters - generate error response
910 $errMessage = $e->getMessageArray();
912 $config = $this->getConfig();
913 // Something is seriously wrong
914 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
915 $info = 'Database query error';
917 $info = "Exception Caught: {$e->getMessage()}";
921 'code' => 'internal_api_error_' . get_class( $e ),
922 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
929 * Replace the result data with the information about an exception.
930 * Returns the error code
931 * @param Exception $e
934 protected function substituteResultWithError( $e ) {
935 $result = $this->getResult();
936 $config = $this->getConfig();
938 $errMessage = $this->errorMessageFromException( $e );
939 if ( $e instanceof UsageException
) {
940 // User entered incorrect parameters - generate error response
941 $link = wfExpandUrl( wfScript( 'api' ) );
942 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
944 // Something is seriously wrong
945 if ( $config->get( 'ShowExceptionDetails' ) ) {
946 ApiResult
::setContentValue(
949 MWExceptionHandler
::getRedactedTraceAsString( $e )
954 // Remember all the warnings to re-add them later
955 $warnings = $result->getResultData( [ 'warnings' ] );
959 $requestid = $this->getParameter( 'requestid' );
960 if ( !is_null( $requestid ) ) {
961 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
963 if ( $config->get( 'ShowHostnames' ) ) {
964 // servedby is especially useful when debugging errors
965 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
967 if ( $warnings !== null ) {
968 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
971 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
973 return $errMessage['code'];
977 * Set up for the execution.
980 protected function setupExecuteAction() {
981 // First add the id to the top element
982 $result = $this->getResult();
983 $requestid = $this->getParameter( 'requestid' );
984 if ( !is_null( $requestid ) ) {
985 $result->addValue( null, 'requestid', $requestid );
988 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
989 $servedby = $this->getParameter( 'servedby' );
991 $result->addValue( null, 'servedby', wfHostname() );
995 if ( $this->getParameter( 'curtimestamp' ) ) {
996 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
997 ApiResult
::NO_SIZE_CHECK
);
1000 $params = $this->extractRequestParams();
1002 $this->mAction
= $params['action'];
1004 if ( !is_string( $this->mAction
) ) {
1005 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1012 * Set up the module for response
1013 * @return ApiBase The module that will handle this action
1014 * @throws MWException
1015 * @throws UsageException
1017 protected function setupModule() {
1018 // Instantiate the module requested by the user
1019 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1020 if ( $module === null ) {
1021 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1023 $moduleParams = $module->extractRequestParams();
1025 // Check token, if necessary
1026 if ( $module->needsToken() === true ) {
1027 throw new MWException(
1028 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1029 'See documentation for ApiBase::needsToken for details.'
1032 if ( $module->needsToken() ) {
1033 if ( !$module->mustBePosted() ) {
1034 throw new MWException(
1035 "Module '{$module->getModuleName()}' must require POST to use tokens."
1039 if ( !isset( $moduleParams['token'] ) ) {
1040 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1043 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1045 $module->encodeParamName( 'token' ),
1046 $this->getRequest()->getQueryValues()
1050 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1051 'found in the query string, but must be in the POST body',
1056 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1057 $this->dieUsageMsg( 'sessionfailure' );
1065 * Check the max lag if necessary
1066 * @param ApiBase $module Api module being used
1067 * @param array $params Array an array containing the request parameters.
1068 * @return bool True on success, false should exit immediately
1070 protected function checkMaxLag( $module, $params ) {
1071 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1072 $maxLag = $params['maxlag'];
1073 list( $host, $lag ) = wfGetLB()->getMaxLag();
1074 if ( $lag > $maxLag ) {
1075 $response = $this->getRequest()->response();
1077 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1078 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1080 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1081 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1084 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1092 * Check selected RFC 7232 precondition headers
1094 * RFC 7232 envisions a particular model where you send your request to "a
1095 * resource", and for write requests that you can read "the resource" by
1096 * changing the method to GET. When the API receives a GET request, it
1097 * works out even though "the resource" from RFC 7232's perspective might
1098 * be many resources from MediaWiki's perspective. But it totally fails for
1099 * a POST, since what HTTP sees as "the resource" is probably just
1100 * "/api.php" with all the interesting bits in the body.
1102 * Therefore, we only support RFC 7232 precondition headers for GET (and
1103 * HEAD). That means we don't need to bother with If-Match and
1104 * If-Unmodified-Since since they only apply to modification requests.
1106 * And since we don't support Range, If-Range is ignored too.
1109 * @param ApiBase $module Api module being used
1110 * @return bool True on success, false should exit immediately
1112 protected function checkConditionalRequestHeaders( $module ) {
1113 if ( $this->mInternalMode
) {
1114 // No headers to check in internal mode
1118 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1119 // Don't check POSTs
1125 $ifNoneMatch = array_diff(
1126 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1129 if ( $ifNoneMatch ) {
1130 if ( $ifNoneMatch === [ '*' ] ) {
1131 // API responses always "exist"
1134 $etag = $module->getConditionalRequestData( 'etag' );
1137 if ( $ifNoneMatch && $etag !== null ) {
1138 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1139 $match = array_map( function ( $s ) {
1140 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1142 $return304 = in_array( $test, $match, true );
1144 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1146 // Some old browsers sends sizes after the date, like this:
1147 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1149 $i = strpos( $value, ';' );
1150 if ( $i !== false ) {
1151 $value = trim( substr( $value, 0, $i ) );
1154 if ( $value !== '' ) {
1156 $ts = new MWTimestamp( $value );
1158 // RFC 7231 IMF-fixdate
1159 $ts->getTimestamp( TS_RFC2822
) === $value ||
1161 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1162 // asctime (with and without space-padded day)
1163 $ts->format( 'D M j H:i:s Y' ) === $value ||
1164 $ts->format( 'D M j H:i:s Y' ) === $value
1166 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1167 if ( $lastMod !== null ) {
1168 // Mix in some MediaWiki modification times
1171 'user' => $this->getUser()->getTouched(),
1172 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1174 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1175 // T46570: the core page itself may not change, but resources might
1176 $modifiedTimes['sepoch'] = wfTimestamp(
1177 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1180 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1181 $lastMod = max( $modifiedTimes );
1182 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1185 } catch ( TimestampException
$e ) {
1186 // Invalid timestamp, ignore it
1192 $this->getRequest()->response()->statusHeader( 304 );
1194 // Avoid outputting the compressed representation of a zero-length body
1195 MediaWiki\
suppressWarnings();
1196 ini_set( 'zlib.output_compression', 0 );
1197 MediaWiki\restoreWarnings
();
1198 wfClearOutputBuffers();
1207 * Check for sufficient permissions to execute
1208 * @param ApiBase $module An Api module
1210 protected function checkExecutePermissions( $module ) {
1211 $user = $this->getUser();
1212 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1213 !$user->isAllowed( 'read' )
1215 $this->dieUsageMsg( 'readrequired' );
1218 if ( $module->isWriteMode() ) {
1219 if ( !$this->mEnableWrite
) {
1220 $this->dieUsageMsg( 'writedisabled' );
1221 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1222 $this->dieUsageMsg( 'writerequired' );
1223 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1225 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1226 'promised-nonwrite-api'
1230 $this->checkReadOnly( $module );
1233 // Allow extensions to stop execution for arbitrary reasons.
1235 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1236 $this->dieUsageMsg( $message );
1241 * Check if the DB is read-only for this user
1242 * @param ApiBase $module An Api module
1244 protected function checkReadOnly( $module ) {
1245 if ( wfReadOnly() ) {
1246 $this->dieReadOnly();
1249 if ( $module->isWriteMode()
1250 && in_array( 'bot', $this->getUser()->getGroups() )
1251 && wfGetLB()->getServerCount() > 1
1253 $this->checkBotReadOnly();
1258 * Check whether we are readonly for bots
1260 private function checkBotReadOnly() {
1261 // Figure out how many servers have passed the lag threshold
1263 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1264 $laggedServers = [];
1265 $loadBalancer = wfGetLB();
1266 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1267 if ( $lag > $lagLimit ) {
1269 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1273 // If a majority of slaves are too lagged then disallow writes
1274 $slaveCount = wfGetLB()->getServerCount() - 1;
1275 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1276 $laggedServers = implode( ', ', $laggedServers );
1279 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1282 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1288 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1294 * Check asserts of the user's rights
1295 * @param array $params
1297 protected function checkAsserts( $params ) {
1298 if ( isset( $params['assert'] ) ) {
1299 $user = $this->getUser();
1300 switch ( $params['assert'] ) {
1302 if ( $user->isAnon() ) {
1303 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1307 if ( !$user->isAllowed( 'bot' ) ) {
1308 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1316 * Check POST for external response and setup result printer
1317 * @param ApiBase $module An Api module
1318 * @param array $params An array with the request parameters
1320 protected function setupExternalResponse( $module, $params ) {
1321 $request = $this->getRequest();
1322 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1323 // Module requires POST. GET request might still be allowed
1324 // if $wgDebugApi is true, otherwise fail.
1325 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1328 // See if custom printer is used
1329 $this->mPrinter
= $module->getCustomPrinter();
1330 if ( is_null( $this->mPrinter
) ) {
1331 // Create an appropriate printer
1332 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1335 if ( $request->getProtocol() === 'http' && (
1336 $request->getSession()->shouldForceHTTPS() ||
1337 ( $this->getUser()->isLoggedIn() &&
1338 $this->getUser()->requiresHTTPS() )
1340 $this->logFeatureUsage( 'https-expected' );
1341 $this->setWarning( 'HTTP used when HTTPS was expected' );
1346 * Execute the actual module, without any error handling
1348 protected function executeAction() {
1349 $params = $this->setupExecuteAction();
1350 $module = $this->setupModule();
1351 $this->mModule
= $module;
1353 if ( !$this->mInternalMode
) {
1354 $this->setRequestExpectations( $module );
1357 $this->checkExecutePermissions( $module );
1359 if ( !$this->checkMaxLag( $module, $params ) ) {
1363 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1367 if ( !$this->mInternalMode
) {
1368 $this->setupExternalResponse( $module, $params );
1371 $this->checkAsserts( $params );
1375 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1377 $this->reportUnusedParams();
1379 if ( !$this->mInternalMode
) {
1380 // append Debug information
1381 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1383 // Print result data
1384 $this->printResult( false );
1389 * Set database connection, query, and write expectations given this module request
1390 * @param ApiBase $module
1392 protected function setRequestExpectations( ApiBase
$module ) {
1393 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1394 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1395 if ( $this->getRequest()->hasSafeMethod() ) {
1396 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1397 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1398 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1399 $this->getRequest()->markAsSafeRequest();
1401 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1406 * Log the preceding request
1407 * @param float $time Time in seconds
1408 * @param Exception $e Exception caught while processing the request
1410 protected function logRequest( $time, $e = null ) {
1411 $request = $this->getRequest();
1414 'ip' => $request->getIP(),
1415 'userAgent' => $this->getUserAgent(),
1416 'wiki' => wfWikiID(),
1417 'timeSpentBackend' => (int) round( $time * 1000 ),
1418 'hadError' => $e !== null,
1424 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1427 // Construct space separated message for 'api' log channel
1428 $msg = "API {$request->getMethod()} " .
1429 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1430 " {$logCtx['ip']} " .
1431 "T={$logCtx['timeSpentBackend']}ms";
1433 foreach ( $this->getParamsUsed() as $name ) {
1434 $value = $request->getVal( $name );
1435 if ( $value === null ) {
1439 if ( strlen( $value ) > 256 ) {
1440 $value = substr( $value, 0, 256 );
1441 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1443 $encValue = $this->encodeRequestLogValue( $value );
1446 $logCtx['params'][$name] = $value;
1447 $msg .= " {$name}={$encValue}";
1450 wfDebugLog( 'api', $msg, 'private' );
1451 // ApiAction channel is for structured data consumers
1452 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1456 * Encode a value in a format suitable for a space-separated log line.
1460 protected function encodeRequestLogValue( $s ) {
1463 $chars = ';@$!*(),/:';
1464 $numChars = strlen( $chars );
1465 for ( $i = 0; $i < $numChars; $i++
) {
1466 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1470 return strtr( rawurlencode( $s ), $table );
1474 * Get the request parameters used in the course of the preceding execute() request
1477 protected function getParamsUsed() {
1478 return array_keys( $this->mParamsUsed
);
1482 * Mark parameters as used
1483 * @param string|string[] $params
1485 public function markParamsUsed( $params ) {
1486 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1490 * Get a request value, and register the fact that it was used, for logging.
1491 * @param string $name
1492 * @param mixed $default
1495 public function getVal( $name, $default = null ) {
1496 $this->mParamsUsed
[$name] = true;
1498 $ret = $this->getRequest()->getVal( $name );
1499 if ( $ret === null ) {
1500 if ( $this->getRequest()->getArray( $name ) !== null ) {
1501 // See bug 10262 for why we don't just implode( '|', ... ) the
1504 "Parameter '$name' uses unsupported PHP array syntax"
1513 * Get a boolean request value, and register the fact that the parameter
1514 * was used, for logging.
1515 * @param string $name
1518 public function getCheck( $name ) {
1519 return $this->getVal( $name, null ) !== null;
1523 * Get a request upload, and register the fact that it was used, for logging.
1526 * @param string $name Parameter name
1527 * @return WebRequestUpload
1529 public function getUpload( $name ) {
1530 $this->mParamsUsed
[$name] = true;
1532 return $this->getRequest()->getUpload( $name );
1536 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1537 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1539 protected function reportUnusedParams() {
1540 $paramsUsed = $this->getParamsUsed();
1541 $allParams = $this->getRequest()->getValueNames();
1543 if ( !$this->mInternalMode
) {
1544 // Printer has not yet executed; don't warn that its parameters are unused
1545 $printerParams = array_map(
1546 [ $this->mPrinter
, 'encodeParamName' ],
1547 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1549 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1551 $unusedParams = array_diff( $allParams, $paramsUsed );
1554 if ( count( $unusedParams ) ) {
1555 $s = count( $unusedParams ) > 1 ?
's' : '';
1556 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1561 * Print results using the current printer
1563 * @param bool $isError
1565 protected function printResult( $isError ) {
1566 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1567 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1570 $printer = $this->mPrinter
;
1571 $printer->initPrinter( false );
1572 $printer->execute();
1573 $printer->closePrinter();
1579 public function isReadMode() {
1584 * See ApiBase for description.
1588 public function getAllowedParams() {
1591 ApiBase
::PARAM_DFLT
=> 'help',
1592 ApiBase
::PARAM_TYPE
=> 'submodule',
1595 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1596 ApiBase
::PARAM_TYPE
=> 'submodule',
1599 ApiBase
::PARAM_TYPE
=> 'integer'
1602 ApiBase
::PARAM_TYPE
=> 'integer',
1603 ApiBase
::PARAM_DFLT
=> 0
1606 ApiBase
::PARAM_TYPE
=> 'integer',
1607 ApiBase
::PARAM_DFLT
=> 0
1610 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1612 'requestid' => null,
1613 'servedby' => false,
1614 'curtimestamp' => false,
1617 ApiBase
::PARAM_DFLT
=> 'user',
1622 /** @see ApiBase::getExamplesMessages() */
1623 protected function getExamplesMessages() {
1626 => 'apihelp-help-example-main',
1627 'action=help&recursivesubmodules=1'
1628 => 'apihelp-help-example-recursive',
1632 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1633 // Wish PHP had an "array_insert_before". Instead, we have to manually
1634 // reindex the array to get 'permissions' in the right place.
1637 foreach ( $oldHelp as $k => $v ) {
1638 if ( $k === 'submodules' ) {
1639 $help['permissions'] = '';
1643 $help['datatypes'] = '';
1644 $help['credits'] = '';
1646 // Fill 'permissions'
1647 $help['permissions'] .= Html
::openElement( 'div',
1648 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1649 $m = $this->msg( 'api-help-permissions' );
1650 if ( !$m->isDisabled() ) {
1651 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1652 $m->numParams( count( self
::$mRights ) )->parse()
1655 $help['permissions'] .= Html
::openElement( 'dl' );
1656 foreach ( self
::$mRights as $right => $rightMsg ) {
1657 $help['permissions'] .= Html
::element( 'dt', null, $right );
1659 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1660 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1662 $groups = array_map( function ( $group ) {
1663 return $group == '*' ?
'all' : $group;
1664 }, User
::getGroupsWithPermission( $right ) );
1666 $help['permissions'] .= Html
::rawElement( 'dd', null,
1667 $this->msg( 'api-help-permissions-granted-to' )
1668 ->numParams( count( $groups ) )
1669 ->params( $this->getLanguage()->commaList( $groups ) )
1673 $help['permissions'] .= Html
::closeElement( 'dl' );
1674 $help['permissions'] .= Html
::closeElement( 'div' );
1676 // Fill 'datatypes' and 'credits', if applicable
1677 if ( empty( $options['nolead'] ) ) {
1678 $level = $options['headerlevel'];
1679 $tocnumber = &$options['tocnumber'];
1681 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1683 // Add an additional span with sanitized ID
1684 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1685 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1688 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1689 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1692 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1693 if ( !isset( $tocData['main/datatypes'] ) ) {
1694 $tocnumber[$level]++
;
1695 $tocData['main/datatypes'] = [
1696 'toclevel' => count( $tocnumber ),
1698 'anchor' => 'main/datatypes',
1700 'number' => implode( '.', $tocnumber ),
1705 // Add an additional span with sanitized ID
1706 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1707 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1710 $header = $this->msg( 'api-credits-header' )->parse();
1711 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1712 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1715 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1716 if ( !isset( $tocData['main/credits'] ) ) {
1717 $tocnumber[$level]++
;
1718 $tocData['main/credits'] = [
1719 'toclevel' => count( $tocnumber ),
1721 'anchor' => 'main/credits',
1723 'number' => implode( '.', $tocnumber ),
1730 private $mCanApiHighLimits = null;
1733 * Check whether the current user is allowed to use high limits
1736 public function canApiHighLimits() {
1737 if ( !isset( $this->mCanApiHighLimits
) ) {
1738 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1741 return $this->mCanApiHighLimits
;
1745 * Overrides to return this instance's module manager.
1746 * @return ApiModuleManager
1748 public function getModuleManager() {
1749 return $this->mModuleMgr
;
1753 * Fetches the user agent used for this request
1755 * The value will be the combination of the 'Api-User-Agent' header (if
1756 * any) and the standard User-Agent header (if any).
1760 public function getUserAgent() {
1762 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1763 $this->getRequest()->getHeader( 'User-agent' )
1767 /************************************************************************//**
1773 * Sets whether the pretty-printer should format *bold* and $italics$
1775 * @deprecated since 1.25
1778 public function setHelp( $help = true ) {
1779 wfDeprecated( __METHOD__
, '1.25' );
1780 $this->mPrinter
->setHelp( $help );
1784 * Override the parent to generate help messages for all available modules.
1786 * @deprecated since 1.25
1789 public function makeHelpMsg() {
1790 wfDeprecated( __METHOD__
, '1.25' );
1793 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1795 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1798 $this->getModuleName(),
1799 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1801 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1802 [ $this, 'reallyMakeHelpMsg' ]
1807 * @deprecated since 1.25
1808 * @return mixed|string
1810 public function reallyMakeHelpMsg() {
1811 wfDeprecated( __METHOD__
, '1.25' );
1814 // Use parent to make default message for the main module
1815 $msg = parent
::makeHelpMsg();
1817 $asterisks = str_repeat( '*** ', 14 );
1818 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1820 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1821 $module = $this->mModuleMgr
->getModule( $name );
1822 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1824 $msg2 = $module->makeHelpMsg();
1825 if ( $msg2 !== false ) {
1831 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1832 foreach ( self
::$mRights as $right => $rightMsg ) {
1833 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1834 ->useDatabase( false )
1835 ->inLanguage( 'en' )
1837 $groups = User
::getGroupsWithPermission( $right );
1838 $msg .= '* ' . $right . " *\n $rightsMsg" .
1839 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1842 $msg .= "\n$asterisks Formats $asterisks\n\n";
1843 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1844 $module = $this->mModuleMgr
->getModule( $name );
1845 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1846 $msg2 = $module->makeHelpMsg();
1847 if ( $msg2 !== false ) {
1853 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1854 $credits = str_replace( "\n", "\n ", $credits );
1855 $msg .= "\n*** Credits: ***\n $credits\n";
1861 * @deprecated since 1.25
1862 * @param ApiBase $module
1863 * @param string $paramName What type of request is this? e.g. action,
1864 * query, list, prop, meta, format
1867 public static function makeHelpMsgHeader( $module, $paramName ) {
1868 wfDeprecated( __METHOD__
, '1.25' );
1869 $modulePrefix = $module->getModulePrefix();
1870 if ( strval( $modulePrefix ) !== '' ) {
1871 $modulePrefix = "($modulePrefix) ";
1874 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1882 * This exception will be thrown when dieUsage is called to stop module execution.
1886 class UsageException
extends MWException
{
1893 private $mExtraData;
1896 * @param string $message
1897 * @param string $codestr
1899 * @param array|null $extradata
1901 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1902 parent
::__construct( $message, $code );
1903 $this->mCodestr
= $codestr;
1904 $this->mExtraData
= $extradata;
1906 // This should never happen, so throw an exception about it that will
1907 // hopefully get logged with a backtrace (T138585)
1908 if ( !is_string( $codestr ) ||
$codestr === '' ) {
1909 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1910 ( $codestr === '' ?
'empty string' : gettype( $codestr ) )
1918 public function getCodeString() {
1919 return $this->mCodestr
;
1925 public function getMessageArray() {
1927 'code' => $this->mCodestr
,
1928 'info' => $this->getMessage()
1930 if ( is_array( $this->mExtraData
) ) {
1931 $result = array_merge( $result, $this->mExtraData
);
1940 public function __toString() {
1941 return "{$this->getCodeString()}: {$this->getMessage()}";
1946 * For really cool vim folding this needs to be at the end:
1947 * vim: foldmarker=@{,@} foldmethod=marker